import { isPc } from '@views/store'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import style from './.module.less'
import pcStyle from './pc.module.less'
export default defineComponent({
    props: {
        modelValue: Number,
        min: Number,
        max: Number
    },
    emits: ['update:modelValue', 'change'],
    setup: (p, { emit }) => {
        let xRange: { x: number, width: number }
        let rate = 1
        const trackRef = ref<HTMLDivElement>()
        const btnRef = ref<HTMLDivElement>()
        const progress = ref(0)
        onMounted(() => {
            nextTick(() => {
                const btnWidth = btnRef.value!.getBoundingClientRect().width
                const { x, width } = trackRef.value!.getBoundingClientRect()
                xRange = { x, width: width - btnWidth }
                // 绑定值和 min max做转换
                const { min = 0, max = 1, modelValue = min } = p
                const valRange = max - min
                rate = valRange / xRange.width

                updateValue((modelValue - min) / rate + x)
            })
        })

        const updateValue = (offsetX: number) => {
            const { x, width } = xRange
            offsetX = offsetX - x
            const val = offsetX < 0 ? 0 : offsetX > width ? width : offsetX
            progress.value = val
            const { min = 0 } = p
            emit('update:modelValue', val * rate + min)
            emit('change', val * rate + min)
        }
        const onClick = (e: MouseEvent) => {
            updateValue(e.offsetX + xRange.x)
        }
        const onTouchmove = (e: TouchEvent) => {
            const { clientX } = e.touches[0]
            updateValue(clientX)
        }
        let canMove = false
        const onMousedown = () => {
            canMove = true
            document.addEventListener('mouseup', onMouseup)
            document.addEventListener('mousemove', onMousemove)
        }
        const onMousemove = (e: MouseEvent) => {
            console.log('move', e.clientX)
            if (!canMove) return
            updateValue(e.clientX)
        }
        const onMouseup = () => {
            canMove = false
            document.removeEventListener('mouseup', onMouseup)
            document.removeEventListener('mousemove', onMousemove)
        }


        return () =>
            <div class={(isPc.value ? pcStyle : style).root}>
                <div ref={trackRef} class='track' onClick={onClick} style={{ '--progress': progress.value + 'px' }} />
                <div ref={btnRef} class="btn" style={{ transform: `translateX(${progress.value}px)` }}
                    onTouchmove={onTouchmove} onMousedown={onMousedown} />
            </div>
    }
})